package com.nuanshui.heatedloan.msgcenter.service;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.msgcenter.integration.MsgTools;
import com.nuanshui.heatedloan.msgcenter.model.*;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.msgcenter.facade.VerificationFacade;
import com.nuanshui.heatedloan.msgcenter.facade.smspush.SmsPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 短信发送 验证处理
 *
 * @author guohao
 * @ClassName: VerificationFacadeImpl
 * @date 2015年4月21日 上午11:47:56
 */
@Service(ServiceConstant.VERIFICATIONFACADE)
public class VerificationFacadeImpl extends CommonServiceImpl implements VerificationFacade {

    private Logger logger = LoggerFactory.getLogger(VerificationFacadeImpl.class);
    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private MsgTools msgTools;

    /**
     * 非线上环境，跳过短信验证
     */
    @Value("${sms.gateway.off}")
    private boolean verifySkip = true;

    @Override
    public VeriCodeResult generateCode(String mobile, AliSmsSecurityCodeTemplateEnum smsTemp, Integer length) {

        if(SysStringUtils.isEmpty(mobile))
        {
            throw new BizException(GlobalErrorCode.UNKNOWN,"手机号码不可为空");
        }

        UserAgent userAgent = this.getUserAgent();
        String safeToken = userAgent.getSafeToken();

        length=(length == null || length == 0) ? 6 : length;

        VeriCode veriCode = new VeriCode(mobile, length);

        if (!veriCode.canSend())
            return new VeriCodeResult(false,length);

        boolean sent = verifySkip;

        if(!sent)
        {
            logger.info("===============放入缓存" + smsTemp.getSessionkeyCode() + safeToken + mobile + "=============");
            jedisUtil.setObjectExpire(smsTemp.getSessionkeyCode() + safeToken + mobile, veriCode, 1800);
            logger.info("===============验证码为" + veriCode.getSmsCode() + "=============");

            SmsPushMsgBody body=new SmsPushMsgBody();
            body.setTemplateCode(smsTemp.getTempCode());
            body.addPhone(mobile);
            body.setBizType(SmsMsg.TYPE_VERICODE.toString());
            body.putParam("code", veriCode.getSmsCode());
            body.putParam("product", "秒借贷");

            msgTools.sendComposeMsg(body);
            sent=true;
        }

        if (sent) {
            veriCode.sent();
        }
        return new VeriCodeResult(sent,length);
    }

    @Override
    public boolean verifyCode(String mobile, String code, AliSmsSecurityCodeTemplateEnum smsTemp) {
        if (verifySkip)
            return true;
        UserAgent userAgent = this.getUserAgent();

        logger.info("VerificationFacadeImpl verifyCode:" + JSON.toJSONString(getUserAgent()));

        String safeToken = userAgent.getSafeToken();
        logger.info("===========验证码为" + code + "=================");
        logger.info("===========手机为" + mobile + "=================");
        logger.info("===========模板为" + smsTemp.getSessionkeyCode() + "=================");
        logger.info("===========总共" + smsTemp.getSessionkeyCode() + safeToken + mobile + "=================");
        VeriCode veriCode = jedisUtil.getObject(smsTemp.getSessionkeyCode() + safeToken + mobile, VeriCode.class);

        logger.info("===========验证码信息为" + JSON.toJSONString(veriCode) + "=================");

        boolean success = veriCode != null && veriCode.verify(mobile, code);
        //清空缓存
        if (success) {
            jedisUtil.del(smsTemp.getSessionkeyCode() + safeToken + mobile);
        }
        return success;
    }
}
